#include<iostream>
#include<vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int diameterOfBinaryTree(TreeNode* root) {
    int res = 0;
    auto dfs = [&](auto&& dfs, TreeNode* cur)->int {
        if (cur == nullptr) return 0;
        int l = dfs(dfs, cur->left);
        int r = dfs(dfs, cur->right);
        res = max(res, l + r + 1);
        return max(l, r) + 1;
        };
    dfs(dfs, root);
    return res - 1;
}